package com.suoluo.zenadmin.controllers.admin.app;

import java.util.List;

import javax.annotation.Resource;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;

import com.suoluo.zenadmin.common.CommonResp;
import com.suoluo.zenadmin.common.JSONPageData;
import com.suoluo.zenadmin.common.PageUtil;
import com.suoluo.zenadmin.common.encrypt.EncryptUtil;
import com.suoluo.zenadmin.controllers.JSONInterceptor.JSON;
import com.suoluo.zenadmin.service.app.AppService;
import com.suoluo.zenadmin.service.dest.DestService;
import com.suoluo.zenadmin.service.hotel.HotelService;
import com.suoluo.zenadmin.vo.PageVO;
import com.suoluo.zenadmin.vo.app.AppInstanceVO;

@Path("/")
public class AppController {

	@Resource(name="appService")
	private AppService appService;
	
	@Resource(name="destService")
	private DestService destService;
	
	@Resource(name="hotelService")
	private HotelService hotelService;
	
	@Get("vlist")
	public String toListApp(){
		return "listApp";
	}
	
	@JSON
	@Post("list")
	public Object findListApp(PageVO page){
		JSONPageData data = new JSONPageData();
		int currpage = page.getPage();
		int rows = page.getRows();
		int startpage = PageUtil.calcStartRow(currpage, rows);
		List<AppInstanceVO> list = appService.findListApp(startpage,rows);
		data.setRows(list);
		
		int total = appService.findAppCount();
		data.setTotal(total);
		return data;
	}
	
	@Get("dest/vsave")
	public String toAddDestApp(){
		return "addDestApp";
	}
	
	@Get("hotel/vsave")
	public String toAddHotelApp(){
		return "addHotelApp";
	}
	
	@JSON
	@Post("save")
	public Object saveApp(AppInstanceVO app){
		//判断是否已经添加过了
		int type = app.getType();
		int dataId = app.getDataId();
		AppInstanceVO appVO = appService.findTokenByTypeAndDataId(type,dataId);
		if(appVO != null){
			CommonResp comm = CommonResp.FAIL;
			comm.setResultMsg("同一应用的版本信息已存在，请修改版本号即可！");
			return comm;
		}
		// 调用md5接口生成一个16位的随机字符串，设置为该应用的token
		String token = EncryptUtil.randomString(16);
		app.setToken(token);
		//添加的应用版本默认是第一版
		app.setVersion(1);
		appService.saveApp(app);
		return CommonResp.SUCCESS;
	}
	
	@Get("vupdate")
	public String toUpdateApp(Invocation inv,@Param("id")int id){
		AppInstanceVO app = appService.findAppInstanceById(id);
		inv.addModel("app",app);
		return "updateApp";
	}
	
	@JSON
	@Post("update")
	public Object updateApp(AppInstanceVO app){
		appService.updateApp(app);
		return CommonResp.SUCCESS;
	}
	
	@JSON
	@Post("all/dest")
	public Object findAllDest(){
		return destService.findAllDest();
	}
	@JSON
	@Post("all/hotel")
	public Object findAllHotel(@Param("destId")int destId){
		return hotelService.findAllHotel(destId);
	}
}
